<?php

/**
 * buildQuery
 * merge params and build query
 * smart for "&"
 */
function buildQuery($params, $name, $value) {
	$params[$name] = $value;
	$query = http_build_query(array_filter($params));
	return empty($query) ? "" : "&" . $query;
}

/**
 * 基于Think\Page通用分页代码
 * @param $m 模型，引用传递
 * @param $where 查询条件
 * @param int $pagesize 每页查询条数
 * @return \Think\Page
 */
function getPage(&$model, $where, $pagesize=10) {
	$modelOriginal=clone $model;										// 先复制一个模型
	$totalsize=$model->where($where)->count();				// 连惯操作后会对join等操作进行重置
	$model=$modelOriginal;											// 为保持在为定的连惯操作，先复制一个模型

	$page=new Think\Page($totalsize, $pagesize);
	$page->lastSuffix=false;
	$page->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>%LIST_ROW%</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
	$page->setConfig('prev', '上一页' );
	$page->setConfig('next', '下一页' );
	$page->setConfig('last', '末页' );
	$page->setConfig('first', '首页' );
	$page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
	
	$page->parameter=I('get.');
	
	$model->limit($page->firstRow, $page->listRows);
	
	return $page;
}

/**
 * 基于扩展Page通用分页代码
 * @param $m 模型，引用传递
 * @param $where 查询条件
 * @param int $pagesize 每页查询条数
 * @return \Page
 */
function getExtPage(&$model, $where, $pagesize=10, $pagetpl) {
	$modelOriginal=clone $model;										// 先复制一个模型
	$totalsize=$model->where($where)->count();						// 连惯操作后会对join等操作进行重置
	$model=$modelOriginal;											// 为保持在为定的连惯操作，先复制一个模型

	// Page
// 	$pagesize = intval($pagesize);
	$page_param = C("VAR_PAGE");
	$pagetpl = empty($pagetpl) ? '{first}{prev}{liststart}{list}{listend}{next}{last}' : $pagetpl;
// 	$pagesetting = array("listlong" => "2", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => "");
// 	$pagesetting = array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => "");
	$pagesetting = array();
	
	$page = new \Page($totalsize, $pagesize);
	$page->setLinkWraper("li");
	$page->__set("PageParam", $page_param);
	$page->SetPager('default', $pagetpl, $pagesetting);

	$model->limit($page->firstRow, $page->listRows);

	return $page;
}

/**
 * 给定内容分页???
 * @param unknown $content
 * @param string $pagetpl
 */
function sp_content_page($content, $pagetpl='{first}{prev}{liststart}{list}{listend}{next}{last}') {
	$contents=explode('_ueditor_page_break_tag_', $content);
	
	$totalsize=count($contents);
	import('Page');
	$pagesize=1;
	$PageParam=C("VAR_PAGE");
	$page=new \Page($totalsize,$pagesize);
	$page->setLinkWraper("li");
	$page->SetPager('default', $pagetpl, array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));

	$data['content']=$contents[$page->firstRow];
	$data['page']=$page->show('default');

	return $data;
}


/**
 * 返回带协议的域名
 */
function sp_get_host() {
	$host=$_SERVER["HTTP_HOST"];
	$protocol=is_ssl()?"https://":"http://";
	return $protocol.$host;
}


/**
 * 获取用户头像相对网站根目录的地址
 */
function sp_get_user_avatar_url($avatar) {

	if ($avatar) {
		if (strpos($avatar, "http")===0) {
			return $avatar;
		} else {
		    if (strpos($avatar, 'avatar/')===false) {
		        $avatar='avatar/'.$avatar;
		    }
		    $url= sp_get_asset_upload_path($avatar,false);
		    if (C('FILE_UPLOAD_TYPE')=='Qiniu') {
		        $storage_setting=sp_get_cmf_settings('storage');
		        $qiniu_setting=$storage_setting['Qiniu']['setting'];
		        $filepath=$qiniu_setting['protocol'].'://'.$storage_setting['Qiniu']['domain']."/".$avatar;
		        if ($qiniu_setting['enable_picture_protect']) {
		            $url=$url.$qiniu_setting['style_separator'].$qiniu_setting['styles']['avatar'];
		        }
		    }
		    
			return $url;
		}

	} else {
		return $avatar;
	}

}

/**
 * XCMS密码比较方法，所有涉及密码比较的地方都用这个方法
 * @param string $password 要比较的密码
 * @param string $passwordInDB 数据库保存的已经加密过的密码
 * @return boolean 密码相同，返回true
 */
function sf_xcms_password($password, $authcode='') {
    if (empty($authcode)) {
        $authcode = C("AUTHCODE");
    }
    return md5(md5($authcode . $password));
}

/**
 * 日志
 * @param unknown $content
 * @param string $file
 */
function sp_log($file="log.txt", $content) {
	file_put_contents($file, $content, FILE_APPEND);
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string($len=6) {
	$chars=array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
			"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
			"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
			"3", "4", "5", "6", "7", "8", "9"
	);
	$charsLen=count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output="";
	for ($i=0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}

/**
 * 清空系统缓存，兼容sae
 */
function clearCache() {
		import ( "ORG.Util.Dir" );
		$dirs = array ();
		// runtime/
		$rootdirs=sp_scan_dir( RUNTIME_PATH . "*" );
		//$noneed_clear=array(".","..","Data");
		$noneed_clear=array(".","..");
		$rootdirs=array_diff($rootdirs, $noneed_clear);
		foreach ( $rootdirs as $dir ) {
			if ($dir != "." && $dir != "..") {
				$dir=RUNTIME_PATH . $dir;
				if (is_dir ( $dir )) {
					//array_push ( $dirs, $dir );
					$tmprootdirs=sp_scan_dir ( $dir."/*" );
					foreach ( $tmprootdirs as $tdir ) {
						if ($tdir != "." && $tdir != "..") {
							$tdir=$dir . '/' . $tdir;
							if (is_dir ( $tdir )) {
								array_push ( $dirs, $tdir );
							} else {
								@unlink($tdir);
							}
						}
					}
				} else {
					@unlink($dir);
				}
			}
		}
		$dirtool=new \Dir("");
		foreach ( $dirs as $dir ) {
			$dirtool->delDir ( $dir );
		}

		if (sp_is_sae()) {
			$global_mc=@memcache_init();
			if ($global_mc) {
				$global_mc->flush();
			}

			$no_need_delete=array("XCMS_DYNAMIC_CONFIG");
			$kv=new SaeKV();
			// 初始化KVClient对象
			$ret=$kv->init();
			// 循环获取所有key-values
			$ret=$kv->pkrget('', 100);
			while (true) {
				foreach($ret as $key =>$value) {
                    if (!in_array($key, $no_need_delete)) {
                    	$kv->delete($key);
                    }
                }
				end($ret);
				$start_key=key($ret);
				$i=count($ret);
				if ($i < 100) break;
				$ret=$kv->pkrget('', 100, $start_key);
			}
		}
}

/**
 * 保存数组变量到php文件
 * @param string $path 保存路径
 * @param mixed $value 要保存的变量
 * @return boolean 保存成功返回true,否则false
 */
function sp_save_var($path,$value) {
	$ret=file_put_contents($path, "<?php\treturn " . var_export($value, true) . ";?>");
	return $ret;
}

/**
 * 更新系统配置文件
 * @param array $data <br>如：array("URL_MODEL"=>0);
 * @return boolean
 */
function sp_set_dynamic_config($data) {

	if (!is_array($data)) {
		return false;
	}

	if (sp_is_sae()) {
		$kv=new SaeKV();
		$ret=$kv->init();
		$configs=$kv->get("XCMS_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result=$kv->set('XCMS_DYNAMIC_CONFIG', serialize($configs));
	} elseif (defined('IS_BAE') && IS_BAE) {
		$bae_mc=new BaeMemcache();
		$configs=$bae_mc->get("XCMS_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result=$bae_mc->set("XCMS_DYNAMIC_CONFIG",serialize($configs),MEMCACHE_COMPRESSED,0);
	} else {
		$config_file="./data/conf/config.php";
		if (file_exists($config_file)) {
			$configs=include $config_file;
		} else {
			$configs=array();
		}
		$configs=array_merge($configs,$data);
		$result=file_put_contents($config_file, "<?php\treturn " . var_export($configs, true) . ";");
	}
	clearCache();
	S("sp_dynamic_config",$configs);
	return $result;
}


/**
 * 转化格式化的字符串为数组 
 * @param string $tag 要转化的字符串,格式如:"id:2;cid:1;order:post_date desc;"
 * @return array 转化后字符串<pre>
 * array(
 *  'id'=>'2',
 *  'cid'=>'1',
 *  'order'=>'post_date desc'
 * )
 */
function sp_param_lable($tag='') {
	$param=array();
	$array=explode(';',$tag);
	foreach ($array as $v) {
		$v=trim($v);
		if (!empty($v)) {
			list($key,$val)=explode(':',$v);
			$param[trim($key)]=trim($val);
		}
	}
	return $param;
}


/**
 * 获取后台管理设置的网站信息
 */
function getSiteSetting() {
	$siteSetting = M("Setting")->find();
	$siteSetting['site_statistics'] = htmlspecialchars_decode($siteSetting['site_statistics']);
	return $siteSetting;
}


function sp_get_upload_setting(){
// 	$upload_setting=sp_get_option('upload_setting');
	if(empty($upload_setting)){
		$upload_setting = array(
				'image' => array(
						'upload_max_filesize' => '10240',//单位KB
						'extensions' => 'jpg,jpeg,png,gif,bmp4'
				),
				'video' => array(
						'upload_max_filesize' => '10240',
						'extensions' => 'mp4,avi,wmv,rm,rmvb,mkv'
				),
				'audio' => array(
						'upload_max_filesize' => '10240',
						'extensions' => 'mp3,wma,wav'
				),
				'file' => array(
						'upload_max_filesize' => '10240',
						'extensions' => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
				)
		);
	}

	if(empty($upload_setting['upload_max_filesize'])){
		$upload_max_filesize_setting=array();
		foreach ($upload_setting as $setting){
			$extensions=explode(',', trim($setting['extensions']));
			if(!empty($extensions)){
				$upload_max_filesize=intval($setting['upload_max_filesize'])*1024;//转化成KB
				foreach ($extensions as $ext){
					if(!isset($upload_max_filesize_setting[$ext]) || $upload_max_filesize>$upload_max_filesize_setting[$ext]*1024){
						$upload_max_filesize_setting[$ext]=$upload_max_filesize;
					}
				}
			}
		}

		$upload_setting['upload_max_filesize']=$upload_max_filesize_setting;
		F("cmf_system_options_upload_setting",$upload_setting);
	}else{
		$upload_setting=F("cmf_system_options_upload_setting");
	}

	return $upload_setting;
}


/**
 * 全局获取验证码图片
 * 生成的是个HTML的img标签
 * @param string $imgparam <br>
 * 生成图片样式，可以设置<br>
 * length=4&font_size=20&width=238&height=50&use_curve=1&use_noise=1<br>
 * length:字符长度<br>
 * font_size:字体大小<br>
 * width:生成图片宽度<br>
 * heigh:生成图片高度<br>
 * use_curve:是否画混淆曲线  1:画，0:不画<br>
 * use_noise:是否添加杂点 1:添加，0:不添加<br>
 * @param string $imgattrs<br>
 * img标签原生属性，除src,onclick之外都可以设置<br>
 * 默认值：style="cursor: pointer;" title="点击获取"<br>
 * @return string<br>
 * 原生html的img标签<br>
 * 注，此函数仅生成img标签，应该配合在表单加入name=verify的input标签<br>
 * 如：&lt;input type="text" name="verify"/&gt;<br>
 */
function sp_verifycode_img($imgparam='length=4&font_size=20&width=238&height=50&use_curve=1&use_noise=1', $imgattrs='style="cursor: pointer;" title="点击获取"') {
	$src = U('Asset/Checkcode/index') . '?' . $imgparam;
	$img = <<<hello
	<img class="verify_img" src="$src" onclick="this.src='$src&time='+Math.random();" $imgattrs/>
hello;
	return $img;
}



/**
 *获取html文本里的img
 * @param string $content
 * @return array
 */
function sp_getcontent_imgs($content) {
	import("phpQuery");
	\phpQuery::newDocumentHTML($content);
	$pq=pq();
	$imgs=$pq->find("img");
	$imgs_data=array();
	if ($imgs->length()) {
		foreach ($imgs as $img) {
			$img=pq($img);
			$im['src']=$img->attr("src");
			$im['title']=$img->attr("title");
			$im['alt']=$img->attr("alt");
			$imgs_data[]=$im;
		}
	}
	\phpQuery::$documents=null;
	return $imgs_data;
}



/**
 * 去除字符串中的指定字符
 * @param string $str 待处理字符串
 * @param string $chars 需去掉的特殊字符
 * @return string
 */
function sp_strip_chars($str, $chars='?<*.>\'\"') {
	return preg_replace('/['.$chars.']/is', '', $str);
}

/**
 * 发送邮件
 * @param string $address
 * @param string $subject
 * @param string $message
 * @return array<br>
 * 返回格式：<br>
 * array(<br>
 * 	"error"=>0|1,//0代表出错<br>
 * 	"message"=> "出错信息"<br>
 * );
 */
function sp_send_email($address,$subject,$message) {
	$mail=new \PHPMailer();
	// 设置PHPMailer使用SMTP服务器发送Email
	$mail->IsSMTP();
	$mail->IsHTML(true);
	// 设置邮件的字符编码，若不指定，则为'UTF-8'
	$mail->CharSet='UTF-8';
	// 添加收件人地址，可以多次使用来添加多个收件人
	$mail->AddAddress($address);
	// 设置邮件正文
	$mail->Body=$message;
	// 设置邮件头的From字段。
	$mail->From=C('SP_MAIL_ADDRESS');
	// 设置发件人名字
	$mail->FromName=C('SP_MAIL_SENDER');;
	// 设置邮件标题
	$mail->Subject=$subject;
	// 设置SMTP服务器。
	$mail->Host=C('SP_MAIL_SMTP');
	//by Rainfer
	// 设置SMTPSecure。
	$Secure=C('SP_MAIL_SECURE');
	$mail->SMTPSecure=empty($Secure)?'':$Secure;
	// 设置SMTP服务器端口。
	$port=C('SP_MAIL_SMTP_PORT');
	$mail->Port=empty($port)?"25":$port;
	// 设置为"需要验证"
	$mail->SMTPAuth=true;
	// 设置用户名和密码。
	$mail->Username=C('SP_MAIL_LOGINNAME');
	$mail->Password=C('SP_MAIL_PASSWORD');
	// 发送邮件。
	if (!$mail->Send()) {
		$mailerror=$mail->ErrorInfo;
		return array("error"=>1,"message"=>$mailerror);
	} else {
		return array("error"=>0,"message"=>"success");
	}
}


function sp_file_write($file,$content) {
	if (sp_is_sae()) {
		$s=new SaeStorage();
		$arr=explode('/',ltrim($file,'./'));
		$domain=array_shift($arr);
		$save_path=implode('/',$arr);
		return $s->write($domain,$save_path,$content);
	} else {
		return file_put_contents($file, $content);
	}
}

function sp_file_read($file) {
	if (sp_is_sae()) {
		$s=new SaeStorage();
		$arr=explode('/',ltrim($file,'./'));
		$domain=array_shift($arr);
		$save_path=implode('/',$arr);
		return $s->read($domain,$save_path);
	} else {
		file_get_contents($file);
	}
}


/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params = array()) {
	tag($hook, $params);
}

/**
 * 处理插件钩子,只执行一个
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook_one($hook,$params=array()) {
    return \Think\Hook::listen_one($hook,$params);
}

/**
 * 替代scan_dir的方法
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 */
function sp_scan_dir($pattern, $flags=null) {
	$files=array_map('basename', glob($pattern, $flags));
	return $files;
}

/**
 * 获取所有钩子，包括系统，应用，模板
 */
function sp_get_hooks($refresh=false) {
	if (!$refresh) {
		$return_hooks=F('all_hooks');
		if (!empty($return_hooks)) {
			return $return_hooks;
		}
	}

	$return_hooks=array();
	$system_hooks=array(
		"url_dispatch","app_init","app_begin","app_end",
		"action_begin","action_end","module_check","path_info",
		"template_filter","view_begin","view_end","view_parse",
		"view_filter","body_start","footer","footer_end","sider","comment",'admin_home'
	);

	$app_hooks=array();

	$apps=sp_scan_dir(APP_PATH."*",GLOB_ONLYDIR);
	foreach ($apps as $app) {
		$hooks_file=APP_PATH.$app."/hooks.php";
		if (is_file($hooks_file)) {
			$hooks=include $hooks_file;
			$app_hooks=is_array($hooks)?array_merge($app_hooks,$hooks):$app_hooks;
		}
	}

	$tpl_hooks=array();

	$tpls=sp_scan_dir("themes/*",GLOB_ONLYDIR);

	foreach ($tpls as $tpl) {
		$hooks_file= addTemplateFileSuffix("themes/$tpl/hooks");
		if (file_exists_case($hooks_file)) {
			$hooks=file_get_contents($hooks_file);
			$hooks=preg_replace("/[^0-9A-Za-z_-]/u", ",", $hooks);
			$hooks=explode(",", $hooks);
			$hooks=array_filter($hooks);
			$tpl_hooks=is_array($hooks)?array_merge($tpl_hooks,$hooks):$tpl_hooks;
		}
	}

	$return_hooks=array_merge($system_hooks,$app_hooks,$tpl_hooks);

	$return_hooks=array_unique($return_hooks);

	F('all_hooks',$return_hooks);
	return $return_hooks;

}


/**
 * 生成访问插件的url
 * @param string $url url 格式：插件名://控制器名/方法
 * @param array $param 参数
 */
function sp_plugin_url($url, $param=array(),$domain=false) {
	$url       =parse_url($url);
	$case      =C('URL_CASE_INSENSITIVE');
	$plugin    =$case ? parse_name($url['scheme']) : $url['scheme'];
	$controller=$case ? parse_name($url['host']) : $url['host'];
	$action    =trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if (isset($url['query'])) {
		parse_str($url['query'], $query);
		$param=array_merge($query, $param);
	}

	/* 基础参数 */
	$params=array(
			'_plugin'     => $plugin,
			'_controller' => $controller,
			'_action'     => $action,
	);
	$params=array_merge($params, $param); //添加额外参数

	return U('api/plugin/execute', $params,true,$domain);
}

/**
 * 检查授权（需要完善+++）
 * @param uid  int           认证用户的id
 * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function sp_auth_check($uid, $name = null, $relation = 'or') {
    return true;
// 	// no need check rules，则无需判断
// 	$rule = MODULE_NAME . CONTROLLER_NAME . ACTION_NAME;
// 	$noNeedCheckRules = ["AdminIndexindex", "AdminMainindex"];
// 	if (in_array($rule, $noNeedCheckRules)) {
// 		return true;
// 	}
		
// 	if (empty($uid)) {
// 		return false;
// 	}

// 	$iauth_obj = new \Common\Lib\iAuth();
// 	if (empty($name)) {
// 		$name = strtolower(MODULE_NAME . "/" . CONTROLLER_NAME . "/" . ACTION_NAME);
// 	}
// 	return $iauth_obj->check($uid, $name, $relation);
}

/**
 * 兼容之前版本的ajax的转化方法，如果你之前用参数只有两个可以不用这个转化，如有两个以上的参数请升级一下
 * @param array $data
 * @param string $info
 * @param int $status
 */
function sp_ajax_return($data,$info,$status) {
	$return=array();
	$return['data']=$data;
	$return['info']=$info;
	$return['status']=$status;
	$data=$return;

	return $data;
}

/**
 * 判断是否为SAE
 */
function sp_is_sae() {
	if (defined('APP_MODE') && APP_MODE=='sae') {
		return true;
	} else {
		return false;
	}
}


function sp_alpha_id($in, $to_num=false, $pad_up=4, $passKey=null) {
	$index="aBcDeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYz0123456789";
	if ($passKey !== null) {
		// Although this function's purpose is to just make the
		// ID short - and not so much secure,
		// with this patch by Simon Franz (http://blog.snaky.org/)
		// you can optionally supply a password to make it harder
		// to calculate the corresponding numeric ID

		for ($n=0; $n<strlen($index); $n++) $i[]=substr( $index,$n ,1);

		$passhash=hash('sha256',$passKey);
		$passhash=(strlen($passhash) < strlen($index)) ? hash('sha512',$passKey) : $passhash;

		for ($n=0; $n < strlen($index); $n++) $p[]= substr($passhash, $n ,1);

		array_multisort($p,  SORT_DESC, $i);
		$index=implode($i);
	}

	$base =strlen($index);

	if ($to_num) {
		// Digital number  <<--  alphabet letter code
		$in =strrev($in);
		$out=0;
		$len=strlen($in) - 1;
		for ($t=0; $t <= $len; $t++) {
			$bcpow=pow($base, $len - $t);
			$out  =$out + strpos($index, substr($in, $t, 1)) * $bcpow;
		}

		if (is_numeric($pad_up)) {
			$pad_up--;
			if ($pad_up > 0) $out -= pow($base, $pad_up);
		}
		$out=sprintf('%F', $out);
		$out=substr($out, 0, strpos($out, '.'));
	} else {
		// Digital number  -->>  alphabet letter code
		if (is_numeric($pad_up)) {
			$pad_up--;
			if ($pad_up > 0) $in += pow($base, $pad_up);
		}

		$out="";
		for ($t=floor(log($in, $base)); $t >= 0; $t--) {
			$bcp=pow($base, $t);
			$a  =floor($in / $bcp) % $base;
			$out=$out . substr($index, $a, 1);
			$in =$in - ($a * $bcp);
		}
		$out=strrev($out); // reverse
	}

	return $out;
}

/**
 * 验证码检查
 * @return boolean <br>true：验证码正确，false：验证码错误
 */
function sp_check_verify_code($verifycode='') {
    $verifycode = empty($verifycode) ? I('request.verify') : $verifycode;
	$verify = new \Think\Verify();
	return $verify->check($verifycode, "");
}

/**
 * 手机验证码检查，验证完后销毁验证码增加安全性 ,<br>返回true验证码正确，false验证码错误
 * @return boolean <br>true：手机验证码正确，false：手机验证码错误
 */
function sp_check_mobile_verify_code($mobile='',$verifycode='') {
    $session_mobile_code=session('mobile_code');
    $verifycode= empty($verifycode)?I('request.mobile_code'):$verifycode;
    $mobile= empty($mobile)?I('request.mobile'):$mobile;
    
    $result= false;
    
    if (!empty($session_mobile_code) && $session_mobile_code['code'] == md5($mobile.$verifycode.C('AUTHCODE')) && $session_mobile_code['expire_time']>time()) {
        $result=true;
    }
    
    return $result;
}


/**
 * 执行SQL文件  sae 环境下file_get_contents() 函数好像有间歇性bug。
 * @param string $sql_path sql文件路径
 * @author 5iymt <1145769693@qq.com>
 */
function sp_execute_sql_file($sql_path) {

	$context=stream_context_create ( array (
			'http' => array (
					'timeout' => 30
			)
	) ) ;// 超时时间，单位为秒

	// 读取SQL文件
	$sql=file_get_contents ( $sql_path, 0, $context );
	$sql=str_replace ( "\r", "\n", $sql );
	$sql=explode ( ";\n", $sql );

	// 替换表前缀
	$orginal='sp_';
	$prefix=C ( 'DB_PREFIX' );
	$sql=str_replace ( "{$orginal}", "{$prefix}", $sql );

	// 开始安装
	foreach ( $sql as $value ) {
		$value=trim ( $value );
		if (empty ( $value )) {
			continue;
		}
		$res=M ()->execute ( $value );
	}
}


/**
 * 给没有后缀的模板文件，添加后缀名
 * @param string $filenameNoSuffix
 */
function addTemplateFileSuffix($filenameNoSuffix) {
    if (file_exists_case($filenameNoSuffix . C('TMPL_TEMPLATE_SUFFIX'))) {
        $filenameNoSuffix = $filenameNoSuffix . C('TMPL_TEMPLATE_SUFFIX');
    } else if (file_exists_case($filenameNoSuffix . ".php")) {
        $filenameNoSuffix = $filenameNoSuffix . ".php";
    } else {
        $filenameNoSuffix = $filenameNoSuffix . C('TMPL_TEMPLATE_SUFFIX');
    }

    return $filenameNoSuffix;
}


/**
 * 判断当前的语言包，并返回语言包名
 */
function sp_check_lang() {
    $langSet=C('DEFAULT_LANG');
    if (C('LANG_SWITCH_ON',null,false)) {

        $varLang= C('VAR_LANGUAGE',null,'l');
        $langList=C('LANG_LIST',null,'zh-cn');
        // 启用了语言包功能
        // 根据是否启用自动侦测设置获取语言选择
        if (C('LANG_AUTO_DETECT',null,true)) {
            if (isset($_GET[$varLang])) {
                $langSet=$_GET[$varLang];// url中设置了语言变量
                cookie('think_language',$langSet,3600);
            } elseif (cookie('think_language')) {// 获取上次用户的选择
                $langSet=cookie('think_language');
            } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {// 自动侦测浏览器语言
                preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
                $langSet=$matches[1];
                cookie('think_language',$langSet,3600);
            }
            if (false === stripos($langList,$langSet)) { // 非法语言参数
                $langSet=C('DEFAULT_LANG');
            }
        }
    }

    return strtolower($langSet);

}

/**
* 删除图片物理路径
* @param array $imglist 图片路径
* @return bool 是否删除图片
* @author 高钦 <395936482@qq.com>
*/
function sp_delete_physics_img($imglist) {
    $file_path=C("UPLOADPATH");

    if ($imglist) {
        if ($imglist['thumb']) {
            $file_path=$file_path . $imglist['thumb'];
            if (file_exists($file_path)) {
                $result=@unlink($file_path);
                if (!$result) {
                    $res=TRUE;
                } else {
                    $res=FALSE;
                }
            } else {
                $res=FALSE;
            }
        }

        if ($imglist['photo']) {
            foreach ($imglist['photo'] as $key => $value) {
                $file_path=C("UPLOADPATH");
                $file_path_url=$file_path . $value['url'];
                if (file_exists($file_path_url)) {
                    $result=@unlink($file_path_url);
                    if (!$result) {
                        $res=TRUE;
                    } else {
                        $res=FALSE;
                    }
                } else {
                    $res=FALSE;
                }
            }
        }
    } else {
        $res=FALSE;
    }

    return $res;
}

/**
 * 安全删除位于头像文件夹中的头像
 *
 * @param string $file 头像文件名,不含路径
 * @author rainfer <81818832@qq.com>
 */
function sp_delete_avatar($file) {
    if ($file) {
		$file='data/upload/avatar/'.$file;
		if (\Think\Storage::has($file)) {
			\Think\Storage::unlink($file);
		}
	}
}

/**
 * 获取惟一订单号
 * @return string
 */
function sp_get_order_sn() {
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 获取惟一订单号（16位）
 * @return string
 */
function sp_get_order_sn_ext() {
    return sp_getYmdHisSSS() . rand(0, 9) . rand(0, 9);
}
function sp_getYmdHisSSS() {
    $cn_time = date('YmdHis', time()) . get_millisecond();
    return $cn_time;
}
function get_millisecond(){
    list($usec, $sec) = explode(" ", microtime());
    $msec = round($usec*1000);
    return $msec;
}


/**
 * 获取文件扩展名
 * @param string $filename
 */
function sp_get_file_extension($filename) {
    $pathinfo=pathinfo($filename);
    return strtolower($pathinfo['extension']);
}

/**
 * 检查手机是否还可以发送手机验证码,并返回生成的验证码
 * @param string $mobile
 */
function sp_get_mobile_code($mobile,$expire_time) {
    if (empty($mobile)) return false;
    $mobile_code_log_model=M('MobileCodeLog');
    $current_time=time();
    $expire_time=(!empty($expire_time)&&$expire_time>$current_time) ? $expire_time:$current_time+60*30;
    $max_count=5;
    $find_log=$mobile_code_log_model->where(array('mobile'=>$mobile))->find();
    $result=false;
    if (empty($find_log)) {
        $result=true;
    } else {
        $send_time=$find_log['send_time'];
        $today_start_time= strtotime(date('Y-m-d',$current_time));
        if ($send_time<$today_start_time) {
            $result=true;
        } else if ($find_log['count']<$max_count) {
            $result=true;
        }
    }
    
    if ($result) {
        $result=rand(100000,999999);
        session('mobile_code',array(
            'code'=>md5($mobile.$result.C('AUTHCODE')),
            'expire_time'=>$expire_time
        ));
    } else {
        session('mobile_code',null);
    }
    return $result;
}

/**
 * 更新手机验证码发送日志
 * @param string $mobile
 */
function sp_mobile_code_log($mobile,$code,$expire_time) {
    
    $mobile_code_log_model=M('MobileCodeLog');
    $find_log=$mobile_code_log_model->where(array('mobile'=>$mobile))->find();
    if ($find_log) {
        $sendtime  =strtotime(date("Y-m-d"));//当天0点
        if ($find_log['send_time']<=$sendtime) {
            $count =1;
        } else {
            $count=array('exp','count+1');
        }
        $result=$mobile_code_log_model->where(array('mobile'=>$mobile))->save(array('send_time'=>time(),'expire_time'=>$expire_time,'code'=>$code,'count'=>$count));
    } else {
        $result=$mobile_code_log_model->add(array('mobile'=>$mobile,'send_time'=>time(),'code'=>$code,'count'=>1,'expire_time'=>$expire_time));
    }
    
    return $result;
}